package com.ce.common.db.loader.impl;

import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import com.ce.common.db.base.DBConnection;
import com.ce.common.db.base.DataObject;
import com.ce.common.db.loader.DatabaseLoader;

/**
 * 读取数据库的表的实现类
 * @author yangenxiong
 *
 */
public class DatabaseLoaderImpl implements DatabaseLoader {

	DBConnection dbConnection;
	
	public DatabaseLoaderImpl() {
		
	}
	
	public DatabaseLoaderImpl(DBConnection dbConnection) {
		this.dbConnection = dbConnection;
	}
	
	public void setDbConnection(DBConnection dbConnection) {
		this.dbConnection = dbConnection;
	}
	
	public DBConnection getDbConnection() {
		return this.dbConnection;
	}
	
	/**
	 * 获取表名称的集合, 参数ignoreTables为不需要的表名, 即获取除ignoreTables外的表名
	 * @param ignoreTables 忽略不需要的表名
	 * @param types 类型, 如: "TABLE", "VIEW"等
	 * @return
	 * @throws Exception
	 */
	public List<DataObject> getTables(String[] types, List<String> ignoreTables)
			throws Exception {
		List<DataObject> tables = getAllTables(types);
		if (ignoreTables != null) {
			List<DataObject> temp = new ArrayList<DataObject>();
			for (String ignoreTable : ignoreTables) {
				DataObject data = new DataObject();
				data.setName(ignoreTable);
				temp.add(data);
			}
			tables.removeAll(temp);
		}
		return tables;
	}
	
	/**
	 * 返回数据库中所有的表集合
	 * @author yangenxiong
	 * @throws Exception
	 */
	public List<DataObject> getAllTables(String[] types) throws Exception {
		return getTables(types);
	}
	
	/**
	 * 根据前缀获取数据库中的表集合
	 * @param types 需要获取的类型
	 * @param prefixs 需要的前缀
	 * @return 封装好的表的对象的集合
	 * @throws Exception
	 */
	public List<DataObject> getTablesByPrefixs(String[] types, String[] prefixs) throws Exception {
		List<DataObject> result = new ArrayList<DataObject>();
		List<DataObject> tables = getTables(types);
		for (DataObject data : tables) {
			for (int i = 0; i < prefixs.length; i++) {
				if (data.getName().toLowerCase().startsWith(prefixs[i].toLowerCase())) {
					result.add(data);
				}
			}
		}
		return result;
	}
	
	
	/**
	 * 获取不符合前缀的表集合
	 * @param types 表的类型
	 * @param prefixs 不符合的表的前缀
	 * @return 封装好的表的对象的集合
	 * @throws Exception
	 */
	public List<DataObject> getTablesWithOutPrefixs(String[] types, String[] prefixs)
			throws Exception {
		List<DataObject> allTables = getTables(types);
		List<DataObject> ignoreTables = getTablesByPrefixs(types, prefixs);
		allTables.removeAll(ignoreTables);
		return allTables;
	}

	/**
	 * 将所有表封装成DataObject集合传出
	 * @param types 表的类型
	 * @return
	 */
	private List<DataObject> getTables(String[] types) {
		ResultSet rs = null;
		List<DataObject> result = new ArrayList<DataObject>();
		try {
			rs = dbConnection.queryTables(types);
			while (rs.next()) {
				result.add(new DataObject(rs.getString(3), rs.getString(4)));
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			dbConnection.closeResultSet(rs);
		}
		return result;
	}
}
